package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.example.common.Constants;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.entity.User;
import com.example.exception.CustomException;
import com.example.mapper.AdminMapper;
import com.example.mapper.UserMapper;
import com.example.mapper.WorkerMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService {
    
    @Resource
    private UserMapper userMapper;

    @Resource
    private AdminService adminService;
    @Resource
    private AdminMapper adminMapper;
    @Resource
    private WorkerService workerService;
    @Resource
    private WorkerMapper workerMapper;

    /**
     * 新增
     */
    public void add(User user) {
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (ObjectUtil.isNotNull(dbUser)) {
            throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
        }
        if (ObjectUtil.isEmpty(user.getPassword())) {
            user.setPassword(Constants.USER_DEFAULT_PASSWORD);
        }
        if (ObjectUtil.isEmpty(user.getName())) {
            user.setName(user.getUsername());
        }
        user.setRole(RoleEnum.USER.name());
        userMapper.insert(user);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            userMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(User user) {
        userMapper.updateById(user);
    }

    /**
     * 根据ID查询
     */
    public User selectById(Integer id) {
        return userMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<User> selectAll(User user) {
        return userMapper.selectAll(user);
    }

    /**
     * 分页查询
     */
    public PageInfo<User> selectPage(User user, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userMapper.selectAll(user);
        return PageInfo.of(list);
    }

    public Account login(Account account) {
        Account dbUser = userMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbUser)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!account.getPassword().equals(dbUser.getPassword())) {
            throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
        }
        // 生成token
        String tokenData = dbUser.getId() + "-" + RoleEnum.USER.name();
        String token = TokenUtils.createToken(tokenData, dbUser.getPassword());
        dbUser.setToken(token);
        return dbUser;
    }

    public void register(Account account, String phone) {
        User user = new User();
        user.setUsername(account.getUsername());
        user.setPassword(account.getPassword());
        user.setName(account.getName());
        user.setAvatar(account.getAvatar());
        user.setPhone(phone);
        this.add(user);  // 插入数据库
    }

    public void updatePassword(Account account) {
        User dbUser = userMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbUser)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!account.getPassword().equals(dbUser.getPassword())) {
            throw new CustomException(ResultCodeEnum.PARAM_PASSWORD_ERROR);
        }
        dbUser.setPassword(account.getNewPassword());
        this.updateById(dbUser);
    }

    public Account getToken(String code) {
        Account dbUser = new Account();

        String access_token = this.getAccessToken();
        // 构建获取token的url
        String userTicket = this.getTicketWithCode(access_token,code);
        String userDetailJson = this.getUserDetailJson(access_token,userTicket);
        JSONObject jsonObject1 = JSONObject.parseObject(userDetailJson);
        String phone = jsonObject1.getString("mobile");
        if(phone!=null){
            dbUser.setPhone(phone);
        }
        dbUser.setAvatar(jsonObject1.getString("avatar"));
        String userId = jsonObject1.getString("userid");

        String userJson = this.getUserJson(access_token,userId);
        // 解析响应json字符串
        JSONObject jsonObject = JSONObject.parseObject(userJson);
        // 企业微信的userId对应系统内userName
        dbUser.setUsername(userId);
        dbUser.setName(jsonObject.getString("name"));
        String deName = this.getDepartment(access_token, jsonObject.getString("main_department"));
        dbUser.setPassword(userId);
        String tokenData = "";
        if("学生".equals(deName)) {
            try{
                this.register(dbUser,phone);
            }catch (Exception e){}
            dbUser.setId(userMapper.selectByUsername(dbUser.getUsername()).getId());
            tokenData = dbUser.getId() + "-" + RoleEnum.USER.name();
            dbUser.setRole(RoleEnum.USER.name());
        }else if("管理员".equals(deName)) {
            try{
                adminService.register(dbUser,phone);
            }catch (Exception e){}
            dbUser.setId(adminMapper.selectByUsername(dbUser.getUsername()).getId());
            tokenData = dbUser.getId() + "-" + RoleEnum.ADMIN.name();
            dbUser.setRole(RoleEnum.ADMIN.name());
        }else if("维修部".equals(deName)) {
            try{
                workerService.register(dbUser,phone);
            }catch (Exception e){}
            dbUser.setId(workerMapper.selectByUsername(dbUser.getUsername()).getId());
            tokenData = dbUser.getId() + "-" + RoleEnum.WORKER.name();
            dbUser.setRole(RoleEnum.WORKER.name());
        }
        // 生成token
        String token = TokenUtils.createToken(tokenData, dbUser.getPassword());
        dbUser.setToken(token);
        return dbUser;
    }

    private String getDepartment(String accessToken, String mainDepartment) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/department/get?" +
                "access_token="+accessToken + "&id=" + mainDepartment;
        // 使用RestTemplate执行GET请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        String responseStr = response.getBody();

        // 解析响应json字符串
        JSONObject jsonObject = JSONObject.parseObject(responseStr);
        // 首先检查department对象是否存在
        JSONObject departmentObject = jsonObject.getJSONObject("department");
        return departmentObject.getString("name");
    }

    private String getUserJson(String accessToken, String userId) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?" +
                "access_token=" + accessToken +
                "&userid=" + userId;
        // 使用RestTemplate执行GET请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        String responseStr = response.getBody();
        return responseStr;
    }

    private String getUserDetailJson(String accessToken, String userTicket) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserdetail?" +
                "access_token=" + accessToken;
        // 构建请求头
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        requestHeaders.setContentType(MediaType.APPLICATION_JSON);
        // 构建动态请求体
        Map<String, String> requestBodyMap = new HashMap<>();
        requestBodyMap.put("user_ticket", userTicket); // 这里可以动态传入user_ticket的值
        // 将Map转换为JSON字符串
        String jsonBody = JSONObject.toJSONString(requestBodyMap);
        // 创建HttpEntity对象
        HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody, requestHeaders);

        // 创建RestTemplate实例
        RestTemplate restTemplate = new RestTemplate();
        // 发送POST请求并获取响应
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

        // 检查响应状态码并处理响应体
        String responseStr = response.getBody();
        return responseStr;
    }

    private String getTicketWithCode(String accessToken, String code) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?" +
                "access_token=" + accessToken +
                "&code=" + code;
        // 使用RestTemplate执行GET请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        String responseStr = response.getBody();

        // 解析响应json字符串
        JSONObject jsonObject = JSONObject.parseObject(responseStr);
        String userTicket = jsonObject.getString("user_ticket");
        return userTicket;
    }

    private String getAccessToken() {
        // 构建URL，包含查询参数
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?" +
                "corpid=wwed13ff8d54add547&" +
                "corpsecret=_0fcBVZIGtG1GXuquy9_1VnQCXy1QatiU2oylhDqNrU";

        // 使用RestTemplate执行GET请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        String responseStr = response.getBody();

        // 解析响应json字符串
        JSONObject jsonObject = JSONObject.parseObject(responseStr);
        String accessToken = jsonObject.getString("access_token");
        return accessToken;
    }
}
